<?php
	include 'include/functions.php';
//set session save path
session_save_path($session_path);
// Initialize a session. 
session_start();
$count++;
$start = time();
$sessionId = session_id();

?>
<!DOCTYPE html PUBLIC "-//W3C//Dtd html 4.01 Transitional//EN"
"http://www.w3.org/tr/html4/loose.dtd">
<html><!-- InstanceBegin template="/Templates/MAIN.dwt.php" codeOutsideHTMLIsLocked="false" -->
  <head>
    <!-- InstanceBeginEditable name="doctitle" -->
    <title>JoshHughes.com NFL Football Pool</title>
    <!-- InstanceEndEditable -->
    <style>
	.underlinecell {
		border-bottom: 2px solid #FF0000;
	}
	.overlinecell {
		border-top: 2px solid #FF0000;
	}
	</style>
	<link rel="stylesheet" href="css/football.css" type="text/css">
    <script src="scripts/prototype.js" type="text/javascript"></script>
	<script src="scripts/scriptaculous.js" type="text/javascript"></script>
	<script type="text/javascript">
	// Dynamic Iframe loader
	function loadmonkeyframe(theURL)
	{
		document.getElementById("monkeyframe").src=theURL;
	}
	function loadpollframe(theURL)
	{
		document.getElementById("pollframe").src=theURL;
	}
	
	// resizes Iframe according to content
	function resizeMe(obj){ 
	docHeight = obj.document.body.scrollHeight
	 obj.style.height = docHeight + 5 + 'px'
	 } 
	</script>
    <!-- InstanceBeginEditable name="head" --><!-- InstanceEndEditable -->
  </head>
<body>
<div id="pagewidth" >
	<div id="header" >
	
		<?PHP include_once("layout/header.html"); ?>
		
	</div>
			<div id="wrapper" class="clearfix" > 
			<div id="maincol" >

			<!-- InstanceBeginEditable name="Contents" -->					
						<table cellpadding="5" cellspacing="0" bgcolor="#FFFFFF">
							<tr>
								<td align="center"><h2>Weekly Breakdown</h2></td>
							</tr>
							<tr>
							<td class="bluebg">
						<?php
						dbConnect();
						//check to see if a Weeknum value was passed, if not, set WeekNum to CurrWeek.
						if (($Weeknum == NULL) || ($Weeknum == ""))
						{
							$Weeknum = getWeek();
								
							//check to make sure $Weeknum > 1 AND $Weeknum < 21
							$Weeknum = checkWeekBounds($Weeknum);
							
							if ((date("w")==2)||(date("w")==3)) //If Tuesday or Wednesday, set Weeknum back one week to review scores.
								if ($Weeknum > 2)
									$Weeknum--;
										
							if (($Weeknum > 17) && (date("w")==1)) //During Playoff time set Weeknum back one week to review scores on Monday also.
								$Weeknum--;
								
						}
						
						//Write SQL Query to extract specified data
						//$SQL = "SELECT * FROM NFLSchedule Where (WEEK=".$Weeknum.") AND (Winner != '-')";
						//Open Record Set using SQL Query
						//$result = mysql_query($SQL) or die("Cannot query the database.<br>" . mysql_error());
						?>
						<form action="<? echo $PHP_SELF; ?>" method="POST" name="WeekForm">
						<table bgcolor="#FFFFFF" callpadding="5" cellspacing="0" width="100%" align="center"><tr>
						<tr><td align="center"><H1><?	getWeekBanner($Weeknum)	?> Results</H1></td>
						<td width="240" align="right" valign="top"><a href="<? echo $PHP_SELF; ?>?Weeknum=<? echo $Weeknum-1; ?>" class="permLink">Prev</a> | <a href="<? echo $PHP_SELF; ?>?Weeknum=<? echo $Weeknum+1; ?>" class="permLink">Next</a> &nbsp; or &nbsp; 
							<B>Go to:</B><?	WeekDropDown($Weeknum)	?>
						</td>
						</tr>
						</table>
						</form>
						
						<table bgcolor="#FFFFFF" border="1" callpadding="5" cellspacing="0" width="100%" align="center">
						<?
						$query="SELECT * FROM NFLSchedule Where (WEEK=".$Weeknum.") ORDER BY GameNum";
						$doQuery=mysql_query($query);
						$numrows=mysql_num_rows($doQuery);
						$num = 1;
						if($numrows > 0)
						{
							while($results=mysql_fetch_array($doQuery))
							{
								//Fill Arrays With Data
								$homeTeams[$num]=$results['Home'];
								$awayTeams[$num]=$results['Away'];
								$winners[$num]=$results['Winner'];
								$num++;
							}
							
							//Print Away Line
							echo "<tr bgcolor=\"#FFFFFF\"><td><b>Away</b></td>";
							foreach($awayTeams as $team)
								echo "<td width=\"40\" align=\"center\"><img src=\"../images/small/".$team.".gif\" alt=\"".$team."\"  title=\"".$team."\" border=\"0\" /></td>";
							echo "<td class=\"underlinecell\" rowspan=\"3\" valign=\"center\" align=\"center\"><b>Week<br/>$Weeknum<br/>Score</b></td>
								<td class=\"underlinecell\" rowspan=\"3\" valign=\"center\" align=\"center\"><b>Magic<br/>#<br/>
								</b></td></tr>";
							
							//Print @ Line
							echo "<tr bgcolor=\"#FFFFFF\"><td>&nbsp;</td>";
							foreach($homeTeams as $team)
							  echo "<td width=\"40\" align=\"center\">@</td>";
							echo "</tr>";
							
							//Print Home Line
							echo "<tr bgcolor=\"#FFFFFF\" bordercolor=\"#172693\"><td class=\"underlinecell\"><b>Home</b></td>";
							foreach($homeTeams as $team)
							  echo "<td class=\"underlinecell\" width=\"40\" align=\"center\"><img src=\"../images/small/".$team.".gif\" alt=\"".$team."\"  title=\"".$team."\" border=\"0\" /></td>";
							echo "</tr>";
							
							$cols = $numrows + 3;
							
							//Print Winner Line
							echo "<tr bgcolor=\"#FFFFFF\"><td class=\"underlinecell\"><span style=\"color: rgb(255, 0, 0); font-weight: bold;\">Winner</span></td>";
							foreach($winners as $team)
								if($team != "-")
									echo "<td class=\"underlinecell\" width=\"40\" align=\"center\"><img src=\"../images/small/".$team.".gif\" alt=\"".$team."\"  title=\"".$team."\" border=\"0\" /></td>";
								else
									echo "<td class=\"underlinecell\" width=\"40\" align=\"center\">&nbsp;</td>";
							echo "<td class=\"underlinecell\">&nbsp;</td><td class=\"underlinecell\" width=\"40\" align=\"center\"><b>".getMagicNum($Weeknum)."</b></td></tr>";
							//Print Rows For User & Picks
							
							$numCorrectPicks = array_fill(1,$numrows, 0);
							$IDs[] = 0;
							$WeeklyScores[] = 0;
							$breakdownString[] = "";
							$totalScore = 0;						
							$totalGuess = 0;						
							
							//Get Data From Users Who Picked
							$UserPickedSQL = "SELECT NFLPicks.*, NFLUsers.username, NFLUsers.ID FROM NFLPicks, NFLUsers WHERE (NFLPicks.Week = ".$Weeknum." AND NFLPicks.UserID = NFLUsers.ID AND (NFLPicks.Game1 IS NOT NULL OR NFLPicks.Game2 IS NOT NULL OR NFLPicks.Game3 IS NOT NULL OR NFLPicks.Game4 IS NOT NULL OR NFLPicks.Game5 IS NOT NULL OR NFLPicks.Game6 IS NOT NULL OR NFLPicks.Game7 IS NOT NULL OR NFLPicks.Game8 IS NOT NULL OR NFLPicks.Game9 IS NOT NULL OR NFLPicks.Game10 IS NOT NULL OR NFLPicks.Game11 IS NOT NULL OR NFLPicks.Game12 IS NOT NULL OR NFLPicks.Game13 IS NOT NULL OR NFLPicks.Game14 IS NOT NULL OR NFLPicks.Game15 IS NOT NULL OR NFLPicks.Game16 IS NOT NULL))  ORDER BY NFLPicks.UserID ASC";
							$UserPickedresult = mysql_query($UserPickedSQL) or die("Cannot query the database.<br>" . mysql_error());
							$row = 0;
							do{
								if ($myrow["UserID"] != NULL)
								{									
									//$breakdownString[$row] = "<td><a href=\"members.php?ID=".$myrow["UserID"]."\" class=\"permLink\" title=\"See the profile on ".$myrow["username"]."\">".$myrow["username"]."</a></td>\n";
									$breakdownString[$row] = "<td>".makeUserLink($myrow["UserID"])."</td>\n";
									$WeeklyScores[$row] = 0;
									$IDs[$row] = $myrow["UserID"];
									for($j = 1; $j <= $numrows; $j++)
									{
										$pick = $myrow["Game".$j];
						
										if($winners[$j] != "-")
										{
											if($pick == $winners[$j])
											{
												$breakdownString[$row].= "<td width=\"40\" align=\"center\"><img src=\"../images/small/".$pick.".gif\" alt=\"".$pick."\" title=\"".$pick."\" border=\"0\" /></td>\n";
												$WeeklyScores[$row]++;
												$numCorrectPicks[$j]++;
											}
											else
											{	
												if($pick == "")
													$breakdownString[$row].= "<td width=\"40\" align=\"center\">&nbsp;</td>\n";
												else
													$breakdownString[$row].= "<td width=\"40\" align=\"center\"><img src=\"../images/red-x.gif\" /></td>\n";
											}
										}
										else
										{
											$InProgressResult = mysql_query("SELECT PickEmailed FROM NFLSchedule WHERE Week=".$Weeknum." AND GameNum=".$j) or die("Cannot query the database.<br>" . mysql_error());
											$ProgressRow = mysql_fetch_array($InProgressResult);
											if($ProgressRow["PickEmailed"] == 1)
												$breakdownString[$row].= "<td width=\"40\" align=\"center\"><img src=\"../images/small/".$pick.".gif\" alt=\"".$pick."\" title=\"".$pick."\" border=\"0\" /></td>\n";
											else
												$breakdownString[$row].= "<td width=\"40\" align=\"center\">&nbsp;</td>\n";
										}
										
									}
									$breakdownString[$row].= "<td align=\"center\"><span style=\"color: rgb(255, 0, 0); font-weight: bold; font-size: 16px;\">$WeeklyScores[$row]</span></td>\n";
									if (AllGamesStarted($Weeknum))
									{
										$breakdownString[$row].= "<td align=\"center\">";
										if ($myrow["MagicNum"] > 0)
											$breakdownString[$row].= $myrow["MagicNum"];
										else
											$breakdownString[$row].= "-";
										$breakdownString[$row].= "</td></tr>\n";
										$totalGuess += $myrow["MagicNum"];
									}
									else
									{
										$breakdownString[$row].= "<td align=\"center\">-</td></tr>\n";
									}
									$totalScore += $WeeklyScores[$row];
									$row++;
								}
								
							}while($myrow = mysql_fetch_array($UserPickedresult));
							// Sort by weekly score
							for($i=sizeof($WeeklyScores); $i>0 /*>= not needed*/; $i--)
							{
								for($i2=1; $i2 <= $i /*<= so includes last*/; $i2++)
								{
									if($WeeklyScores[$i2-1] < $WeeklyScores[$i2])
									{
										swapthese($WeeklyScores[$i2-1],$WeeklyScores[$i2]);
										swapthese($breakdownString[$i2-1],$breakdownString[$i2]);
										swapthese($IDs[$i2-1],$IDs[$i2]);
									};
									
								}
							}
							// PRint the lines
							for ($num = 0; $num <= sizeof($breakdownString); $num++)
							{
								if ($userID)
								{
									if ($userID == $IDs[$num])
										echo "<tr bgcolor=\"#ffff33\">".$breakdownString[$num];
									else
										echo "<tr bgcolor=\"".getRowColor($num)."\">".$breakdownString[$num];
								}
								else
								{
									echo "<tr bgcolor=\"".getRowColor($num)."\">".$breakdownString[$num];
								}
							}
							
							// Print last rows of table
							echo "<tr bgcolor=\"".getRowColor($row)."\">";
							echo "<td class=\"overlinecell\" align=\"right\"><b>Total</b><br/>($row users)</td>\n";
							for ($j = 1; $j <= $numrows; $j++)
								echo "<td class=\"overlinecell\" width=\"40\" align=\"center\">$numCorrectPicks[$j]</td>\n";
							echo "<td class=\"overlinecell\" align=\"center\"><b>Avg</b><br/>".round($totalScore/$row, 1)."</td>\n";
							echo "<td class=\"overlinecell\" align=\"center\"><b>Avg</b><br/>".round($totalGuess/$row, 1)."</td>\n";
							echo "</tr>\n";
						}
						else
						{
							print '<tr bgcolor=\"#FFFFFF\"><td colspan=\"$cols\" align=\"center\">No Games Set for This Week Yet.</td></tr>';
						}
						//Close table
						echo "</table>";
						?>
						</td>
						<tr><td>&nbsp;</td></tr>
						<tr><td>
						<div class="redbg" style="padding: 2px;">
							<table width="100%" cellpadding="0" cellspacing="0" border="0">
								<tr>
									<td align="left"><span class="whitelink">View Game Scores</span></td>
									<td align="right"><img src="images/showhide.gif" title="Show/Hide Scores" alt="Show/Hide Scores" border="0"  onclick="new Effect.toggle('scoresframe', 'blind');" /></td>
								</tr>
							</table><iframe style="display:none;" id="scoresframe" name="scoresframe" src="../rss/week<?= $Weeknum; ?>.xml" height="350" width="100%" frameborder="0" scrolling="no" ></iframe>
						</div>
						</td></tr>
						</tr>
						</table><br/>
					
			<!-- InstanceEndEditable -->
			
			</div>
			<div id="leftcol" >
			
				<?PHP include_once("layout/left_column.php"); ?>
		
			</div>
			
		</div>
		
		<div id="footer" >
		
			<?PHP include_once("layout/footer.html"); ?>
			
		</div>
</div>
</body>
<!-- InstanceEnd --></html>